#!/usr/bin/env node
'use strict';

/*
 * This script normalizes the given spec in examples/specs and
 * writes the full normalized spec to `examples/specs/normalized`
 * if the normalized spec is different than the original.
 * We output this to a different folder so that build-examples script does not generate
 * redundant Vega output specs.
 */

const fs = require('fs');
const vl = require('../build/vega-lite');
const stableStringify = require('fast-json-stable-stringify');
const compactStringify = require('json-stringify-pretty-compact');

const args = require('yargs').demand(0).argv;

const DIR = __dirname + '/..';
const SPECS = '/examples/specs';

const example = args._[0] || '/dev/stdin';
if (example && example.includes('.vl.json')) {
  const path = DIR + SPECS + '/' + example;
  const spec = JSON.parse(fs.readFileSync(path));

  const preNormalized = stableStringify(spec);
  const fullSpec = vl.normalize(spec);
  const postNormalized = stableStringify(fullSpec);

  // console.log(preNormalized, postNormalized);
  if (preNormalized !== postNormalized) {
    const postNormalizedOutput = compactStringify(fullSpec);
    // -8 is cutting .vl.json
    const newFilename = example.slice(0, -8) + '_normalized.vl.json';
    const newFilenameAndPath = DIR + SPECS + '/normalized/' + newFilename;
    fs.writeFile(newFilenameAndPath, postNormalizedOutput, err => {
      if (err) return console.log(err);
      console.log('Built:', newFilename);
    });
  }
}
